package test;

import com.netflix.hystrix.*;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;

import java.util.Calendar;

/**
 * describe:
 *
 * @author helloworldyu
 * @date 2018/11/13
 */
public class CacheCommand extends HystrixCommand<String> {
	private String id;

	/**
	 * 命令名
	 */
	private static final HystrixCommandKey GETTER_KEY = HystrixCommandKey.Factory.asKey("CacheCommandKey");

	protected CacheCommand( String id ) {
		super( Setter
			.withGroupKey( HystrixCommandGroupKey.Factory.asKey( "CacheGroupKey" ) )
			.andCommandKey( GETTER_KEY )
			.andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("CacheThreadPool")));

		this.id = id;
	}

	@Override
	protected String run() throws Exception {
		return id + Calendar.getInstance().getTime().getTime();
	}


	@Override
	protected String getCacheKey() {
		return id;
	}


	/**
	 * 清空 id 为 id 的缓存
	 * @param id id
	 */
	public static void flushCache(String id){
		HystrixRequestCache.getInstance(GETTER_KEY, HystrixConcurrencyStrategyDefault.getInstance()).clear(id);
	}


	public static void main(String[] args) throws InterruptedException {
		//初始化上下文
		HystrixRequestContext context = HystrixRequestContext.initializeContext();

		CacheCommand cacheCommand = new CacheCommand("1");
		String result = cacheCommand.execute();
		System.out.println( "result: " + result );
		Thread.sleep(100);

		//cacheKey 相同，从缓存获取 value
		CacheCommand cacheCommand1 = new CacheCommand("1");
		String result1 = cacheCommand1.execute();
		System.out.println( "result1: " + result1 );
		Thread.sleep(100);

		//cacheKye 不命中，不能从缓存中获取 value
		CacheCommand cacheCommand2 = new CacheCommand("2");
		String result2 = cacheCommand2.execute();
		System.out.println( "result2: " + result2 );

		Thread.sleep(100);
		//结束上下文
		//!!!!!!!!清空缓存,所以 id 为1 的缓存数据不存在了
		flushCache("1");
		CacheCommand cacheCommand3 = new CacheCommand("1");
		String result3 = cacheCommand3.execute();
		System.out.println("result3: " + result3 );

		context.shutdown();
	}
}